<template>
  <el-dialog v-model="visible" :title="title" width="780" show-footer show-zoom resize @close="close" :close-on-click-modal="false">
    <template #default>
      <el-form ref="formRef" :model="form" label-align="right" inline label-width="120" size="default" class="form" label-position="top">
        <el-form-item label="指标" required>
          <el-select style="width: 350px" v-model="form.performanceIndicator.indicator_type" collapse-tags placeholder="指标" clearable @change="indicatorTypeChange">
            <el-option v-for="item in props.options.basePerformanceIndicator?.indicator_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="期望目标" required class="mr-[0]">
          <VGroup>
            <el-input
              style="width: 250px"
              v-model="form.performanceIndicator.desired_target"
              placeholder="请输入期望目标"
              @blur="blurApportion"
              oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
            ></el-input>
            <span style="display: grid" v-show="[1, 2, 3, 6].includes(form.performanceIndicator.indicator_type)">
              <SelectCurrency style="width: 100px; height: 100%" v-model="form.performanceIndicator.currency_id" placeholder="币种" @change="changeCurrency"> </SelectCurrency>
            </span>
            <span class="pl-2" v-show="form.performanceIndicator.indicator_type == 4 || form.performanceIndicator.indicator_type == 5">%</span>
          </VGroup>
        </el-form-item>
        <el-form-item label="时间范围" required>
          <el-date-picker
            v-model="form.performanceIndicator.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="max-width: 350px"
            :default-time="defaultTime()"
            @change="changeDay"
          />
        </el-form-item>
        <el-form-item label="所属部门/人员" required class="mr-[0]">
          <select-personnel style="width: 350px" v-model="form.performanceIndicator.department_user_id" placeholder="所属部门/人员" :multiple="true" @change="changeIndicatorList"></select-personnel>
        </el-form-item>
      </el-form>
      <el-table :data="form.indicatorList" border style="width: 100%" highlight-current-row height="400">
        <el-table-column prop="user_name" label="人员" />
        <el-table-column prop="name" label="个人目标" width="200">
          <template #default="{ row }">
            <div class="flex items-center w-[100%]">
              <el-input class="mr-1 flex-1" v-model="row.individual_target" @change="changeTarget($event, row)"></el-input>
              <div class="w-30">{{ unit }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="日均目标" width="180">
          <template #default="{ row }"> {{ row.average_daily_target }}{{ unit }} </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="100">
          <template #default="{ row, $index }">
            <el-button type="danger" link @click="handleDelete(row, $index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #footer>
      <div v-if="handleType == 'view'">
        <el-button @click="close">关闭</el-button>
      </div>
      <div v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { createPerformanceIndicator, updatePerformanceIndicator, getPerformanceIndicatorDetail } from "../api/index"
import { reactive, ref, toRefs, getCurrentInstance, computed } from "vue"
import { ElMessage, ElSelect } from "element-plus"
import { filterDayApart } from "@/utils/config.js"
import SelectCurrency from "@/components/Selects/SelectCurrency"
import { deepClone } from "@/utils/index.js"

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(["query"])
const props = defineProps({
  options: {
    type: Object,
    default: () => {},
  },
})

const unit = computed(() => {
  if ([1, 2, 3, 6].includes(form.value.performanceIndicator.indicator_type)) {
    return form.value.performanceIndicator.currency
  } else {
    return "%"
  }
})
const indicatorTypeChange = (e) => {
  if ([1, 2, 3, 6].includes(e)) {
    form.value.performanceIndicator.currency_id = 35
  }
}

const data = reactive({
  form: {},
  title: "新增",
  handleType: null,
  daysApart: 1,
})
const { form, title, handleType, daysApart } = toRefs(data)

const statusMap = new Map([
  ["add", "新增"],
  ["edit", "编辑"],
  ["view", "查看"],
  ["copy", "新增"],
])
const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    performanceIndicator: {},
    indicatorList: [],
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getPerformanceIndicatorDetail({
      id,
    })
    if (handleType.value == "copy") {
      const performanceIndicator = res.data.performanceIndicator
      performanceIndicator.timeRange = [performanceIndicator.start_time, performanceIndicator.end_time]
      delete performanceIndicator.create_time
      delete performanceIndicator.create_user
      delete performanceIndicator.update_time
      delete performanceIndicator.update_user
      delete performanceIndicator.id
      delete performanceIndicator.is_delete

      form.value = {
        indicatorList: res.data.indicatorList,
        performanceIndicator,
      }
    } else {
      res.data.performanceIndicator.timeRange = [res.data.performanceIndicator.start_time, res.data.performanceIndicator.end_time]
      form.value = res.data
    }
  } catch (e) {
    throw Error(e)
  }
}

// 数组遍历不存在增加
const matchAndGenerate = (array1, array2) => {
  var result = []

  // 创建一个映射，用于根据id查找list1中的项
  const idMap = {}
  for (const item1 of array1) {
    idMap[item1.user_id] = item1
  }

  // 遍历list2中的项，如果list1中存在相同id的项，则使用list1中的数据，否则使用list2中的数据
  for (const item2 of array2) {
    if (idMap[item2.user_id]) {
      result.push(idMap[item2.user_id])
    } else {
      result.push(item2)
    }
  }

  return result
}

const changeIndicatorList = async (list) => {
  if (list.length) {
    const indicatorList = []
    list.forEach((i) => {
      if (i.value) {
        indicatorList.push({
          user_name: i.text,
          user_id: i.value,
          department_user_id: i.data.department_user_id,
          individual_target: "",
          average_daily_target: "",
        })
      }
    })

    if (form.value.indicatorList.length > 0) {
      form.value.indicatorList = matchAndGenerate(form.value.indicatorList, indicatorList)
    } else {
      form.value.indicatorList = indicatorList
    }
    blurApportion()
  } else {
    form.value.indicatorList = []
  }
}

const changeDay = async (val) => {
  if (val.length) {
    const day = filterDayApart(val[0], val[1])
    daysApart.value = day + 1
    blurApportion()
  }
}

const changeTarget = async (val, row) => {
  if ([1, 2, 3, 6].includes(form.value.performanceIndicator.indicator_type)) {
    const average = (row.individual_target / (daysApart.value || 1)).toFixed(2)
    row.average_daily_target = average
    calculateSum()
  } else {
    row.average_daily_target = row.individual_target
  }
}

const handleDelete = async (row, index) => {
  const findIndex = form.value.performanceIndicator.department_user_id.findIndex((i) => i == row.user_id)
  console.log(form.value.performanceIndicator.department_user_id)
  console.log(findIndex)
  if (findIndex !== -1) {
    let newItems = deepClone(form.value.performanceIndicator.department_user_id)
    newItems.splice(findIndex, 1)
    form.value.performanceIndicator.department_user_id = newItems
  }
  form.value.indicatorList.splice(index, 1)
  calculateSum()
}

const calculateSum = () => {
  form.value.performanceIndicator.desired_target = form.value.indicatorList.reduce((pre, cur) => {
    return pre + Number(cur.individual_target || 0)
  }, 0)
}

const changeCurrency = async (val) => {
  form.value.performanceIndicator.currency = val
}

// 修改期望目标 分摊
const blurApportion = async (val) => {
  if (form.value.performanceIndicator.desired_target == 0) {
    form.value.performanceIndicator.desired_target = ""
    return
  }
  if (form.value.indicatorList?.length == 0) {
    return
  }
  if ([1, 2, 3, 6].includes(form.value.performanceIndicator.indicator_type)) {
    const minuteAverage = (form.value.performanceIndicator.desired_target / form.value.indicatorList?.length).toFixed(2)
    const average = (minuteAverage / (daysApart.value || 1)).toFixed(2)
    form.value.indicatorList.forEach((i) => {
      i.individual_target = minuteAverage
      i.average_daily_target = average
    })
  } else {
    form.value.indicatorList.forEach((i) => {
      i.individual_target = form.value.performanceIndicator.desired_target
      i.average_daily_target = form.value.performanceIndicator.desired_target
    })
  }
}

const save = () => {
  if (!form.value.performanceIndicator.indicator_type) {
    ElMessage.error("请选择指标")
    return
  }
  if (!form.value.performanceIndicator.desired_target) {
    ElMessage.error("请输入期望目标")
    return
  }
  if ([1, 2, 3, 6].includes(form.value.performanceIndicator.indicator_type) && !form.value.performanceIndicator.currency_id) {
    ElMessage.error("请输入币种")
    return
  }
  if (!form.value.performanceIndicator.timeRange) {
    ElMessage.error("请选择时间范围")
    return
  }
  if (!form.value.performanceIndicator.department_user_id) {
    ElMessage.error("请选择所属部门/人员")
    return
  }

  form.value.performanceIndicator.start_time = form.value.performanceIndicator.timeRange[0]
  form.value.performanceIndicator.end_time = form.value.performanceIndicator.timeRange[1]

  if (form.value.performanceIndicator.id) {
    updatePerformanceIndicator(form.value)
      .then((res) => {
        ElMessage.success(res.message)
        emits("query")
        close()
      })
      .finally((e) => {
        loading.value = false
      })
  } else {
    createPerformanceIndicator(form.value)
      .then((res) => {
        ElMessage.success(res.message)
        emits("query")
        close()
      })
      .finally((e) => {
        loading.value = false
      })
  }
}

const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped></style>
